var window = floaty.rawWindow(
  <frame gravity="center" bg="#ff00ff">
    <button id="action" w="300dp" h="300dp">
      按钮
    </button>
  </frame>
);
setInterval(() => {}, 1000);

var execution = null;

//记录按键被按下时的触摸坐标
var x = 0,
  y = 0;
//记录按键被按下时的悬浮窗位置
var windowX, windowY;
//记录按键被按下的时间以便判断长按等动作
var downTime;

let windowWidth;
let windowHeight;
ui.post(function () {
  windowWidth = window.getWidth();
  windowHeight = window.getHeight();
}, 1000);

window.action.setOnTouchListener(function (view, event) {
  switch (event.getAction()) {
    case event.ACTION_DOWN:
      x = event.getRawX();
      y = event.getRawY();
      windowX = window.getX();
      windowY = window.getY();
      downTime = new Date().getTime();
      return true;
    case event.ACTION_MOVE:
      //移动手指时调整悬浮窗位置
      let xAxisMovingDistance = event.getRawX() - x;
      let yAxisMovingDistance = event.getRawY() - y;
      if (windowX + xAxisMovingDistance < 0) {
        if (windowY + yAxisMovingDistance < 0) {
          window.setPosition(0, 0);
        } else if (windowY + windowHeight + yAxisMovingDistance > device.height) {
          window.setPosition(0, device.height - windowHeight);
        } else {
          window.setPosition(0, windowY + yAxisMovingDistance);
        }
      } else if (windowX + xAxisMovingDistance > device.width - windowWidth) {
        if (windowY + yAxisMovingDistance < 0) {
          window.setPosition(device.width - windowWidth, 0);
        } else if (windowY + windowHeight + yAxisMovingDistance > device.height) {
          window.setPosition(device.width - windowWidth, device.height - windowHeight);
        } else {
          window.setPosition(device.width - windowWidth, windowY + yAxisMovingDistance);
        }
      } else {
        if (windowY + yAxisMovingDistance < 0) {
          window.setPosition(windowX + xAxisMovingDistance, 0);
        } else if (windowY + windowHeight + yAxisMovingDistance > device.height) {
          window.setPosition(windowX + xAxisMovingDistance, device.height - windowHeight);
        } else {
          window.setPosition(windowX + xAxisMovingDistance, windowY + yAxisMovingDistance);
        }
      }
      return true;

    case event.ACTION_UP:
      //手指弹起时如果偏移很小则判断为点击
      if (Math.abs(event.getRawY() - y) < 5 && Math.abs(event.getRawX() - x) < 5) {
        onClick();
      }
      return true;
  }
  return true;
});

function onClick() {
  toastLog("作者: 牙叔");
}
